<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>


    <style>
        html,
        body {
            width: 100%;
            height: 100%;
            margin: 0 auto;
            padding: 0;
            display: flex;
            justify-content: center;
            align-items: center;
        }

        *,
        *::before,
        *::after {
            -webkit-box-sizing: border-box;
            box-sizing: border-box;
        }

        #app {
            width: 1000px;
            height: 800px;
            display: flex;
            flex-direction: row;
            justify-content: center;
            align-items: center;
            border: 1px orangered solid;
            padding: 10px;
            background-color: lightslategray;
        }

        .canvas_container {
            display: flex;
            /* width: 1000px;
            height: 800px; */
            background-color: lightgray;
            position: relative;
        }

        .char_area_container {
            display: flex;
            flex-direction: column;
            flex: 1;
            height: 100%;
            margin-left: 12px;
            background-color: lightsteelblue;
            padding: 0px 10px;
        }

        button {
            padding: 8px 10px;
            background-color: lightseagreen;
            border-radius: 4px;
            color: white;
            border: none;
            outline: none;
            cursor: pointer;
        }

        button.active {
            background-color: orangered;
            cursor: pointer;
        }

        [v-cloak] {
            display: none !important;
        }

        .canvas_mask {
            position: absolute;
            width: 100%;
            height: 100%;
            background-color: lightpink;
            opacity: 0.2;
        }

        .right_line {
            height: 50px;
            width: 100%;
            display: flex;
            justify-content: flex-start;
            align-items: center;
        }



        .area_line_each {
            line-height: 30px;
            display: flex;
            flex-direction: row;
            padding: 10px;
            background-color: lightseagreen;
            margin-top: 1px;

        }

        .area_line_each>div {
            line-height: 30px;
        }

        .area_line_each_line {
            display: flex;
            flex-direction: row;
        }

        .item_right {
            flex: 1;
            display: flex;
            align-items: center;
        }

        .item_tool {
            width: 250px;
            display: flex;

        }

        .mr_5 {
            margin-right: 10px;
        }

        .mr_10 {
            margin-right: 10px;
        }
    </style>

</head>

<body>

    <div id="app" v-cloak>
        <div class="canvas_container" id="canvas_container">
            <canvas id="canvas" width='413' height='500'></canvas>
            <!-- <div v-if="!selectMode" class="canvas_mask"></div> -->
        </div>
        <div class="char_area_container">
            <div class="right_line">

                <button v-if="selectMode" @click="changeSelectMode" class="mr_10 active">
                    退出框选
                </button>
                <button v-if="!selectMode" @click="changeSelectMode" class="mr_10 ">
                    激活框选
                </button>

                <button v-if="!delMode" @click="changeDelMode()" class="mr_10">
                    激活删除
                </button>
                <button v-if="delMode" @click="changeDelMode()" class="mr_10 active">
                    退出删除
                </button>

                <button @click="saveClick" class="mr_10">
                    全部保存
                </button>

            </div>
            <div class="area_line_container">
                <div v-for="react in reactList" class="area_line_each">
                    <div class="area_line_each_line">
                        <div class="item_tool">
                            <el-select v-model="react.id" filterable remote reserve-keyword placeholder="请搜索选择字"
                                :remote-method="remoteMethod" :loading="loading">
                                <el-option v-for="item in options" :key="item.id" :label="item.label" :value="item.id">
                                </el-option>
                            </el-select>
                        </div>
                        <div class="item_right">{{react.from_x}}|{{react.from_y}}|{{react.to_x}}|{{react.to_y}}</div>
                    </div>

                </div>
                <div v-if="reactList.length>0">注:测试请输入任意字母,用于模拟远程搜索</div>
            </div>

        </div>



    </div>

    <script src="https://cdn.staticfile.org/vue/2.2.2/vue.min.js"></script>

    <script src="https://cdn.bootcss.com/fabric.js/3.4.0/fabric.js"></script>

    <!-- 引入样式 -->
    <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
    <!-- 引入组件库 -->
    <script src="https://unpkg.com/element-ui/lib/index.js"></script>

    <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>

    <script>
        var canvas = new fabric.Canvas('canvas'); //声明画布
        canvas.selection = false;
        canvas.skipTargetFind = true;
        canvas.selectable = false;

        canvas.defaultCursor = 'crosshair'; //默认光标改成十字
        canvas.hoverCursor = 'crosshair'; //默认光标改成十字
        // canvas.hoverCursor = 'pointer'; //悬浮光标改成手型

        var url = "http://223.68.159.69:1001/Images/beitie/寒食帖.png";
        // url = "1.jpg"

        var canvas_container_dom = document.getElementById("canvas_container");


        fabric.Image.fromURL(url, function (oImg) {

            oImg.width = oImg._element.width;
            oImg.height = oImg._element.height;

            // canvas.setWidth(oImg.width * 0.5);
            // canvas.setHeight(oImg.height * 0.5);

            // canvas_container_dom.style.width = oImg.width * 0.5 + "px";
            // canvas_container_dom.style.height = oImg.height * 0.5 + "px";

            oImg.preserveObjectStacking = true;

            // oImg.scaleX = 0.5;
            // oImg.scaleY = 0.5;

            oImg.crossOrigin = 'anonymous';

            oImg.selectable = false;

            canvas.add(oImg)

        });

  

        window.zoom = window.zoom ? window.zoom : 1;
        var drawWidth = 2; //笔触宽度
        var color = "#E34F51"; //画笔颜色
        var canvasObjectIndex = 0;
        var drawingObject = null; //当前绘制对象
        var moveCount = 1; //绘制移动计数器
        var doDrawing = false; // 绘制状态
        var mouseFrom = {};


        var mouseTo = {};

        //坐标转换
        function transformMouse(mouseX, mouseY) {
            return {
                x: mouseX / window.zoom,
                y: mouseY / window.zoom
            };
        }

        canvas.on("selection:created", function (e) {
            console.log(e.target, "=========e.target==========");
            console.log(e.target.index, "=========e.target.index==========");

            canvas.remove(e.target);
            canvas.discardActiveObject(); //清楚选中框

            var positionIndex = -1;
            vueApp.reactList.forEach((element, i) => {
                if (element.id == e.target.index) {
                    positionIndex = i;

                    //如果不是为new开头就是未保存的
                    if (element.id.indexOf("new_") > -1) {

                    }
                    vueApp.delIdsArr.push(element.id);
                    return;
                }
            });
            console.log(positionIndex);
            var arr = vueApp.reactList;
            arr.splice(positionIndex, 1);
            console.log(arr, "=======arr=========");

            vueApp.reactList = arr;
        });

        //绑定画板事件
        canvas.on("mouse:down", function (options) {

            if (vueApp.selectMode && !vueApp.delMode) {
                var xy = transformMouse(options.e.offsetX, options.e.offsetY);
                mouseFrom.x = xy.x;
                mouseFrom.y = xy.y;
                doDrawing = true;
            }


        });

        canvas.on('mouse:up', function (options) {
            console.log("=====mouse:up=======");
            if (vueApp.delMode) {
                return;
            }
            var xy = transformMouse(options.e.offsetX, options.e.offsetY);
            mouseTo.x = xy.x;
            mouseTo.y = xy.y;
            // drawing();
            drawingObject = null;
            moveCount = 1;
            doDrawing = false;
            vueApp.reactList.push({
                id: canvasObjectIndex,
                text: '',
                from_x: mouseFrom.x,
                from_y: mouseFrom.y,
                to_x: mouseTo.x,
                to_y: mouseTo.y
            });
        })

        canvas.on("mouse:move", function (options) {
            if (moveCount % 2 && !doDrawing) {
                //减少绘制频率
                return;
            }
            moveCount++;
            var xy = transformMouse(options.e.offsetX, options.e.offsetY);
            mouseTo.x = xy.x;
            mouseTo.y = xy.y;
            drawing();
        });

        function drawing() {
            if (drawingObject) {
                canvas.remove(drawingObject);
            }

            var canvasObject = null;
            var path =
                "M " +
                mouseFrom.x +
                " " +
                mouseFrom.y +
                " L " +
                mouseTo.x +
                " " +
                mouseFrom.y +
                " L " +
                mouseTo.x +
                " " +
                mouseTo.y +
                " L " +
                mouseFrom.x +
                " " +
                mouseTo.y +
                " L " +
                mouseFrom.x +
                " " +
                mouseFrom.y +
                " z";
            var left = mouseFrom.x,
                top = mouseFrom.y;
            console.log(path, "========path=========");
            canvasObject = new fabric.Path(path, {
                left: left,
                top: top,
                stroke: color,
                strokeWidth: drawWidth,
                fill: "rgba(255, 255, 255, 0)"
            });
            if (canvasObject) {
                canvas.add(canvasObject);
                var newGuid = "new_" + new Date().getTime();
                canvasObject.index = newGuid;
                canvasObjectIndex = newGuid;
                console.log(canvasObject.index);
                drawingObject = canvasObject;
            }
        }
        var vueApp = new Vue({
            el: '#app',
            data: function () {
                return {
                    visible: false,
                    selectMode: false,
                    delMode: false,
                    reactList: [],
                    options: [],
                    value: [],
                    list: [],
                    loading: false,
                    states: [{
                            label: 'Alabama',
                            id: 1
                        },
                        {
                            label: 'Connecticut',
                            id: 2
                        }, {
                            label: 'Delaware',
                            id: 3
                        }, {
                            label: 'Florida',
                            id: 4
                        }

                    ],
                    delIdsArr: []
                }
            },
            mounted() {
                this.list = this.states.map(item => {
                    return {
                        value: item.id,
                        label: item.label
                    };
                });

                this.getBeiTieData();
            },
            methods: {
                initCanvas() {},
                drawing: function (arr) {

                    var arr = [{
                            CoordsId: '111',
                            BeitieId: '',
                            WordId: '',
                            FromX: 0,
                            FromY: 0,
                            ToX: 100,
                            ToY: 80,
                        },
                        {
                            CoordsId: '222',
                            BeitieId: '',
                            WordId: '',
                            FromX: 150,
                            FromY: 22,
                            ToX: 300,
                            ToY: 200,
                        }, {
                            CoordsId: '333',
                            BeitieId: '',
                            WordId: '',
                            FromX: 150,
                            FromY: 400,
                            ToX: 300,
                            ToY: 450,
                        }
                    ];


                    var item = arr[0];

                    var path =
                        "M " +
                        item.FromX +
                        " " +
                        item.FromY +
                        " L " +
                        item.ToX +
                        " " +
                        item.FromY +
                        " L " +
                        item.ToX +
                        " " +
                        item.ToY +
                        " L " +
                        item.FromX +
                        " " +
                        item.ToY +
                        " L " +
                        item.FromX +
                        " " +
                        item.FromY +
                        " z";
                    var left = item.FromX,
                        top = item.FromY;
                    console.log(path, "========path=========");
                    canvasObject = new fabric.Path(path, {
                        left: left,
                        top: top,
                        stroke: color,
                        strokeWidth: drawWidth,
                        fill: "rgba(255, 255, 255, 0)"
                    });
                    if (canvasObject) {
                        canvas.add(canvasObject);
                        var newGuid = item.CoordsId
                        canvasObject.index = newGuid;
                        canvasObjectIndex = newGuid;
                        console.log(canvasObject.index);
                        drawingObject = canvasObject;
                    }

                },
                getBeiTieData() {


                    //模拟有数据
                    this.reactList.push({
                        CoordsId: '23233424-34343434-343434',
                        BeitieId: '101',
                        WordId: '1',
                        FromX: '0',
                        FromY: '0',
                        ToX: '200',
                        ToY: '100'
                    });

                    //还原框选状态
                    this.drawing(this.reactList);



                    return false;

                    $.ajax({
                        type: "GET",
                        url: "/Beitie/GetBeitieCoordsListById?keyword=",
                        contentType: "application/json",
                        success: function (data) {


                            console.log(data, "============data============");
                        },
                        error: function (data) {
                            console.log(data, "============error============");
                        }

                    });
                },
                saveClick() {
                    this.changeDelMode(false);
                    this.selectMode = false;

                    var arr = [];
                    arr.push({
                        CoordsId: '',
                        BeitieId: '',
                        WordId: '',
                        FromX: '',
                        FromY: '',
                        ToX: '',
                        ToY: ''
                    });

                    $.ajax({
                        type: "POST",
                        url: "/Beitie/SaveBeitieWordCoords",
                        contentType: "application/json",
                        data: arr,
                        success: function (data) {
                            //弹框关闭或刷新
                            console.log(data, "============data============");
                        },
                        error: function (data) {
                            console.log(data, "============error============");
                        }

                    });
                },
                changeSelectMode() {

                    if (this.selectMode) {
                        this.selectMode = false;
                    } else {
                        this.selectMode = true;
                    }

                    this.changeDelMode(false);
                },

                changeDelMode(toMode) {

                    if (toMode == undefined) {
                        toMode = !this.delMode;
                    }

                    if (toMode) {
                        this.delMode = true;
                        canvas.selection = true;
                        canvas.skipTargetFind = false;
                        canvas.selectable = true;
                    } else {
                        this.delMode = false;
                        canvas.selection = false;
                        canvas.skipTargetFind = true;
                        canvas.selectable = false;
                    }

                },
                remoteMethod(query) {
                    if (query !== '') {
                        this.loading = true;
                        setTimeout(() => {
                            this.loading = false;
                            this.options = this.list.filter(item => {
                                return item.label.toLowerCase()
                                    .indexOf(query.toLowerCase()) > -1;
                            });
                        }, 200);
                    } else {
                        this.options = [];
                    }
                }
            }
        })
    </script>

</body>

</html>